$(document).ready(function(){
	indexRunner = 1;
	
	doCallAjaxReadFile();

	
	//alert(liveFeedString);
	$('.list').empty();
	

	
	
	//--Switch Tab
	$('.tabs #logout').click(function(){
		window.location = 'mcot_login/administrator/logout.php';
	});
	
	$('.tabs #save').click(function(){
		readResultFeed();
		var jsonStr = '';
		var haveRelease = false;
		jsonStr += '{';
		jsonStr += outputFeedString;
		refreshGroupIdList();

		var fwdFlag = false;
		var skip = 0;
		

		
		for(var i=0;i<groupIdList.length;i++){
			var idx = groupIdList[i]; 

			
			if(outputReleaseList[idx] == undefined ){

			}else{
				haveRelease =true;
				if(i == 0){
                    jsonStr += ',"channelList":[';
            }
            if(i != 0 /*&& i!=groupIdList.length-1*/ ){jsonStr += (',');}
            

            for(var j=0;j<outputReleaseList[idx].length;j++){

                    if(outputReleaseList[idx] == undefined){
                    	continue;
                    }
                    else{
                    	jsonStr += outputReleaseList[idx][j];	
                    }
                    if(j<outputReleaseList[idx].length-1 && outputReleaseList[idx].length > 1 ){
                            jsonStr += ',';
                    }
            }
            

    }//end else
			

		}
	//If do not have any release do not append ']'.	
	if(haveRelease){
		jsonStr += ']';
	}		
	jsonStr += '}';
	writeFile(jsonStr);
	
	});
	
	
	
	
	
	$('.tabs #typeList').click(function(){
		switchTo($('#edit-wrapper'));
		$('.tabs #typeList').removeClass().addClass('lockpos').css({'color': '#fff'});
		$('.tabs #releaseList').removeClass().addClass('unlockpos').css({'color': '#666'});		
	});
	
	
	
	
	
	$('.tabs #releaseList').click(function(){
		
		switchTo($('#release-wrapper'));
		$('.tabs #releaseList').removeClass().addClass('lockpos').css({'color': '#fff'});
		$('.tabs #typeList').removeClass().addClass('unlockpos').css({'color': '#666'});;


		refreshGroupIdList();
		$('select[name="r-id"]').empty();

		$.each(groupIdList,function(index,value){
			$('select[name="r-id"]').append('<option value = '+value+'>'+groupNameList[index]+'</option>');
		});
		
		refreshReleaseList();
	});
	
	
	
	
	$('#release-wrapper select[name="r-id"]').change(function(){
		refreshReleaseList();
	});
	
	
	
	
	$('.tabs #viewResult').click(function(){
		switchTo($('#result-wrapper'));
			readResultFeed();
			var haveRelease = false;
			$('#result-wrapper').empty();
			$('#result-wrapper').append('{');
			$('#result-wrapper').append(outputFeedString);
			refreshGroupIdList();
			for(var i=0;i<groupIdList.length;i++){
				var idx = groupIdList[i]; 
				if(outputReleaseList[idx] == undefined ){
				}else{
					haveRelease =true;
					if(i == 0){
						$('#result-wrapper').append(',"channelList":['); 
					}
					if(i!=0){$('#result-wrapper').append(',');}
					for(var j=0;j<outputReleaseList[idx].length;j++){
						$('#result-wrapper').append(outputReleaseList[idx][j]);
						if(j<outputReleaseList[idx].length-1){
							$('#result-wrapper').append(',');
						}
					}
					

				}//end else
			}
		//If do not have any release do not append ']'.	
		if(haveRelease){
			$('#result-wrapper').append(']');
		}		
		$('#result-wrapper').append('}');
	});
	//>
	
	
	
	//--Set initail tabs
	$('#edit-wrapper , #release-wrapper , #result-wrapper').hide('fast');
	$('#edit-wrapper').show('fast');


	//--Onchage Image URL field
	$("input[name='image-url']").change(function(){
		$('.release-place-holder img').attr('src',$("input[name='image-url']").val());
	});
	
	


	
	
	$('a.add-new-group-list').live('click',function(){
		var object = $('#group-list-item-stuff').clone().attr('id','');
		var inputx = new Array();
		inputx[0] = $("input[name='g-id']");
		inputx[1] = $("input[name='g-name']");
		inputx[2] = $("textarea[name='g-description']");
		
		refreshGroupIdList();
		
		if(   isNaN(parseInt(inputx[0].val()))   ){
			('You must assign ID with number');
		}if(checkDuplicateID( parseInt(inputx[0].val()) )){
			('Duplicated ID');
		}else if(!checkBlank(inputx)){
			object.find('#g-id').html("ID :: "+parseInt(inputx[0].val()));			
			object.find('#g-name').html("Name :: "+inputx[1].val());
			object.find('#g-description').html("Description :: "+inputx[2].val());
			
			var count = $("li.group-list-item").size() ;
			object.find('#order').html(count);

			//assemble(inputx);
			$('.group-list').append(object);	

			//*******************************************************************************************************8
			outputReleaseList[ parseInt(inputx[0].val()) ]= undefined;
			for(var i = 0; i<inputx.length; i++)inputx[i].val("");

		}
		
		//updateReleaseList();
	});
	
	
	
	


	$('a.add-new-release-list').live('click',function(){
		var object = $('#release-list-item-stuff').clone().attr('id','');
		var inputx = new Array();
		inputx[0] = $("select[name='r-id']");
		inputx[1] = $("input[name='r-idx']");
		inputx[2] = $("input[name='r-name']");
		inputx[3] = $("input[name='r-url']");
		inputx[4] = $("input[name='image-url']");
		
		inputx[5] = $("select[name='r-mode']");
		
		
		
		
			if(!checkBlank(inputx)){
			object.find('#l-id').html("Group ID :: "+inputx[0].val());			
			object.find('#l-idx').html("ID :: "+inputx[1].val());
			object.find('#l-name').html("Name :: "+inputx[2].val());
			object.find('#l-url').html("Play URL :: "+inputx[3].val());
			object.find('#l-image').html("Image URL :: "+inputx[4].val());
			object.find('img').attr('src',inputx[4].val());
			
			object.find('#l-mode').html("Mode :: "+inputx[5].val());
			

			var idx = inputx[0].val();
			var temp = '{"id":'+inputx[1].val()+',"logo":"'+inputx[4].val()+'","mode":'+inputx[5].val()+','+'"playUrl":"'+inputx[3].val()+'","name":"'+inputx[2].val()+'","typeId":'+inputx[0].val()+'}';
			
			if(outputReleaseList[idx] == undefined){
				outputReleaseList[idx] = new Array();
				zeroChildCount[idx]=0;
				outputReleaseList[idx][zeroChildCount[idx]++] = temp;
			}else{
				outputReleaseList[idx][zeroChildCount[idx]++] = temp;
			}

			$('.list').append(object);	

			$('.release-place-holder img').attr('src','');
			for(var i = 0+1; i<inputx.length; i++)inputx[i].val("");
		}
		
		
	});
	

	$(function() {
	        $(".group-list").sortable({
	            placeholder: "ui-state-highlight",
	            revert: true,
				update: function (event, ui) {
				
				changeIndex();
				}
         	 });
	        $(".group-list").disableSelection();
			
				$('#g-id-zip,#l-id-zip').keypress(function() {
			var key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
			if ((key > 57 || key <= 47) && (key != 13) && (key != 46)) {
				event.returnValue = false;
				('Press numeric key only');
			}
		});
			
	    });
	
	  $('a.up-button').live("click", function() {
	        var clickIndex = $(this).parents("li").index();
	        var current = $("li.group-list-item").eq(clickIndex);
			current.prev().before(current);
			var beforeC = clickIndex-1;
			$("li.group-list-item:eq(" +clickIndex+") div.drag-area").empty().append(clickIndex+1);
			$("li.group-list-item:eq(" +beforeC+") div.drag-area").empty().append(clickIndex);
			
	    });
		
		$('a.down-button').live("click", function() {
			var clickIndex = $(this).parents("li").index() -1;
			var current = $("li.group-list-item").eq(clickIndex);
			current.next().after(current);
			var afterC = clickIndex+1;
			$("li.group-list-item:eq(" +clickIndex+") div.drag-area").empty().append(afterC);
			$("li.group-list-item:eq(" +afterC+") div.drag-area").empty().append(afterC+1);
	    });
		
		$('a.delete-button').live("click", function() {
			if(confirm("Do you want to delete this list?"))
			{
				var clickIndex = $(this).parents("li").index() ;
				$(this).parents("li").remove();

		refreshGroupIdList();
				for(var x = 0; x<outputReleaseList.length; x++ ){
				
					var skipFlag = true;
					for(var n=0; n<groupIdList.length; n++){
						if(groupIdList[n]==x)skipFlag = false;
					}
					
					if(skipFlag){
						//skip
						outputReleaseList[x] == undefined;
					}

						if(x==clickIndex)continue;
						outputReleaseList.push(templist[x]);
				}
				
				
				changeIndex();
				
			}
	    });
		
		$('a.delete-button-l').live("click", function() {
		    if(confirm("Do you want to delete this list?"))
			{
				var clickIndex = $(this).parents("li").index() ;
				$(this).parents("li").remove();
				
				var idx = $('#release-wrapper select[name="r-id"] option:selected').val();	
				
				if(clickIndex == 0){
					outputReleaseList[idx].shift();

				}else{
					outputReleaseList[idx].splice(clickIndex,clickIndex);

				}
				changeIndex();
				
			}
	    });
		
		
	
		
	
});


function readResultFeed(){
	
	outputFeedString = "";	
	var inputx = new Array();
	var cntx = 0;

	
	outputFeedString = '"typeList":[';
	
	
	$(".group-list li:not(.action li)").each(function(n) {

		var desc = $(this).find("#g-description").html();
		desc = desc.substring(desc.lastIndexOf(" :: ")+4);
		
		var id = $(this).find("#g-id").html();
		id = id.substring(id.lastIndexOf(" :: ")+4);
		
		var name = $(this).find("#g-name").html();
		name = name.substring(name.lastIndexOf(" :: ")+4);
		


        var temp = '{"id":'+id+',"name":"'+name+'","description":"'+desc+'"}';
        outputFeedString += temp;

     	cntx++;
     	
     	if(cntx < $('.group-list').children().size() ){
 			outputFeedString += ",";
 		}
     	
	 });
	 
	outputFeedString += ']';
	

}







function changeIndex()
{
	var count = $("li.group-list-item").size() - 1;
	for(var i = 0; i<count; i++)
	{
		$("li.group-list-item:eq(" +i+") div.drag-area").empty().append(i+1);
	}
}




function checkBlank(list){	
	for(var i = 0; i<list.length; i++){
		if(list[i].val() == ""){
			return true;
		}
	}
	return false;
}





function refreshGroupIdList(){
	groupIdList = new Array();
	groupNameList = new Array();
	
	$(".group-list li:not(.action li)").each(function(n) {
		var id = $(this).find("#g-id").html();
		var name = $(this).find("#g-name").html();
		
		id = id.substring(id.lastIndexOf(" :: ")+4);
		name = name.substring(name.lastIndexOf(" :: ")+4);
		
		groupIdList.push(id);
		groupNameList.push(name);
		
		//(groupNameList);
	 });
	
}




function checkDuplicateID(Id){
	for(var i=0;i<groupIdList.length;i++){
		if(groupIdList[i]==Id)return true;
	}return false;
}








function refreshReleaseList(){
	$('.list').empty();
	
	var idx = $('#release-wrapper select[name="r-id"] option:selected').val();
	
	for( var i=0; i<outputReleaseList[idx].length ;i++ ){
	
		var nx = outputReleaseList[idx][i];
		
		var jsonx = jQuery.parseJSON(nx);
		var object = $('#release-list-item-stuff').clone().attr('id','');
		
		object.find('#l-id').html("<b style='color:#4a007d'>Group ID</b> :: "+jsonx.typeId);			
		object.find('#l-idx').html("<b style='color:#4a007d'>ID</b> :: "+jsonx.id);
		object.find('#l-mode').html("<b style='color:#4a007d'>Mode</b> :: "+jsonx.mode);
		object.find('#l-name').html("<b style='color:#4a007d'>Name</b> :: "+jsonx.name);
		object.find('#l-url').html("<b style='color:#4a007d'>Play URL</b> :: "+jsonx.playUrl);
		object.find('#l-image').html("<b style='color:#4a007d'>Image URL</b> :: "+jsonx.logo);
		object.find('img').attr('src',jsonx.logo);

		
		$('.list').append(object);

	}
}


function writeFile(content){
	
	document.getElementById('hidden_content_to_save').value=content;
	setTimeout(document.forms["save_json_form"].submit(),5000);
//	document.forms["save_json_form"].submit();	
}


function switchTo(visibleElement){
	$('#edit-wrapper , #release-wrapper , #result-wrapper').hide('fast');
	visibleElement.show('fast');
}




function doCallAjaxReadFile() {
	
	  HttPRequest = false;
	  if (window.XMLHttpRequest) { // Mozilla, Safari,...
		 HttPRequest = new XMLHttpRequest();
		 if (HttPRequest.overrideMimeType) {
			HttPRequest.overrideMimeType('text/html');
		 }
	  } else if (window.ActiveXObject) { // IE
		 try {
			HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
		 } catch (e) {
			try {
			   HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		 }
	  } 
	  
	  if (!HttPRequest) {
		 alert('Cannot create XMLHTTP instance');
		 return false;
	  }

	  var url = 'read_file.php';
	  var pmeters = "rFile="+"live.json";

		HttPRequest.open('POST',url,true);

		HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		HttPRequest.setRequestHeader("Content-length", pmeters.length);
		HttPRequest.setRequestHeader("Connection", "close");
		HttPRequest.send(pmeters);
					
		HttPRequest.onreadystatechange = function()
		{

			 if(HttPRequest.readyState == 3)  // Loading Request
			  {
			  }

			 if(HttPRequest.readyState == 4) // Return Request
			  {	
				 liveFeedString = HttPRequest.responseText;

				 //draw initiai list
				 liveFeedGroupObject = (jQuery.parseJSON(liveFeedString)).typeList;
				 liveFeedListObject = (jQuery.parseJSON(liveFeedString)).channelList;
				 

				 for(var i=0; i< liveFeedGroupObject.length; i++){
					 
					 	var object = $('#group-list-item-stuff').clone().attr('id','');
						
					 	object.find('#g-id').html("<b style='color:#4a007d'>Group ID</b> :: "+parseInt(liveFeedGroupObject[i].id));			
						object.find('#g-name').html("<b style='color:#4a007d'>Group Name</b> :: "+liveFeedGroupObject[i].name);
						object.find('#g-description').html("<b style='color:#4a007d'>Group Description</b> :: "+liveFeedGroupObject[i].description);

						
						var count = $("li.group-list-item").size() ;
						object.find('#order').html(count);

						//assemble(inputx);
						object.attr('id','');
						$('.group-list').append(object);
				 }
				 for(var i=0; i< liveFeedListObject.length; i++){

					 	var idx = liveFeedListObject[i].typeId;

						var temp = '{"id":'+liveFeedListObject[i].id+',"logo":"'+liveFeedListObject[i].logo+'","mode":'+liveFeedListObject[i].mode+',"playUrl":"'+liveFeedListObject[i].playUrl+'","name":"'+liveFeedListObject[i].name+'","typeId":'+liveFeedListObject[i].typeId+'}';

						if(outputReleaseList[idx] == undefined){
							outputReleaseList[idx] = new Array();
							zeroChildCount[idx]=0;
							outputReleaseList[idx][zeroChildCount[idx]++] = temp;
						}else{
							outputReleaseList[idx][zeroChildCount[idx]++] = temp;
						}
				 }
				 
				 
			  }				
		}

 }//end ReadFile




var outputFeedString ='';
var outputReleaseFeedString ='';
var groupIdList = new Array();
var groupNameList = new Array();


var outputReleaseList = new Array();
var zeroChildCount = new Array(0);

var liveFeedGroupObject;// = (jQuery.parseJSON(liveFeedString)).typeList;
var liveFeedListObject;// = (jQuery.parseJSON(liveFeedString)).releaseList;
